<template>
  <view class="question_wrapper">
    <!-- 答题组件使用swiper轮播组件开发，可以支持左右滑动选题功能。 -->
    <swiper
      class="question_swiper"
      :current="current"
      @change="handleSwiperChange"
      :indicator-dots="false"
      :autoplay="false"
      :interval="3000"
      :duration="500"
    >
      <swiper-item v-for="(question, index) in questions" :key="index">
        <view class="question_content">
          <!-- 题干部分 -->
          <view class="question_item_name">
            <text class="question_item_type">{{ question.type }}</text>
            {{ index + 1 }}. {{ question.content }}
          </view>

          <!-- 选项部分 -->
          <view v-for="option in question.optionsList" :key="option" class="question_item_option"
            :class="{'selected': isOptionSelected(question, option[0])}"
            @tap="handleAnswer(question, option[0])">
            <text>{{ option[0] }}. {{ option.substring(2) }}</text>
          </view>

          <!-- 解析部分，答完题后展示解析 -->
          <view v-if="question.answered" class="question_item_parse">
            <view>正确答案： <text style="color:#6db786;font-weight: bold;">{{ question.answer }} </text></view>
          </view>
        </view>
      </swiper-item>
    </swiper>

    <!-- 底部操作栏 -->
    <view class="question_bar">
      <view class="question_bar_icon_wrapper">
        <image @tap="handleCard" class="question_bar_icon" src="../../static/menu.svg" mode="aspectFill"></image>
      </view>

      <!-- 页码 -->
      <view class="question_bar_info">
        {{ current + 1 }} / {{ questions.length }}
      </view>

      <!-- 导航按钮 -->
      <view class="question_bar_nav">
        <button 
          class="nav_button" 
          :disabled="current === 0"
          @tap="handlePrev"
        >上一题</button>
        <button 
          class="nav_button" 
          :disabled="current === questions.length - 1"
          @tap="handleNext"
        >下一题</button>
      </view>

      <!-- 提交按钮 -->
      <view class="question_bar_submit" v-if="canSubmit">
        <button class="submit_button" @tap="handleSubmit">提交答案</button>
      </view>
    </view>

    <!-- 隐藏的答题卡 -->
    <view v-if="cardVisible" class="question_card">
      <view
        v-for="(question, index) in questions"
        :key="index"
        :class="['question_card_point', { current: index === current, right: question.answered && question.right, error: question.answered && !question.right }]"
        @tap="handleJump(index)"
      >
        {{ index + 1 }}
      </view>
      <view class="question_card_submit">
        <button class="submit_button" @tap="handleSubmit">提交答案</button>
      </view>
    </view>
  </view>
</template>

<script>
import { submitAnswers } from '../../service/api.js';
import { getBaseUrl } from '../../config.js';

export default {
  data() {
    return {
      // 当前题目列表
      questions: [],
      // 当前是第几题
      current: 0,
      // 答题卡可见性
      cardVisible: false,
      chapterId: null,
      subjectId: null,
      // 答题计时相关
      answerTimes: {},
      // 防止重复点击
      isNavigating: false,
      // 提交按钮状态
      canSubmit: false
    };
  },
  onLoad(options) {
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.redirectTo({ url: '/pages/login/index' });
      return;
    }
    
    this.chapterId = options.categoryId;
    this.subjectId = options.subjectId;
    this.fetchQuestions();
  },
  onShow() {
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.redirectTo({ url: '/pages/login/index' });
    }
  },
  methods: {
    // 答题卡跳转指定题目
    handleJump(index) {
      this.current = index;
      this.cardVisible = false;
    },
    // 展示答题卡
    handleCard() {
      this.cardVisible = !this.cardVisible;
    },
    // 上一题
    handlePrev() {
      if (this.current > 0) {
        this.recordEndTime(this.current);
        this.current--;
        this.recordStartTime(this.current);
      }
    },
    // 下一题
    handleNext() {
      if (this.current < this.questions.length - 1) {
        this.recordEndTime(this.current);
        this.current++;
        this.recordStartTime(this.current);
      }
    },
    // 轮播改变事件，记录当前索引
    handleSwiperChange(e) {
      const newIndex = e.detail.current;
      this.recordEndTime(this.current);
      this.current = newIndex;
      this.recordStartTime(this.current);
      // 检查是否可以提交
      this.checkSubmitStatus();
    },
    // 回答题目
    handleAnswer(question, option) {
      if (question.answered) return;

      question.answered = true;
      question.right = question.answer === option;
      question.selectedOption = option;

      this.$set(this.questions, this.questions.indexOf(question), question);
      this.checkSubmitStatus();

      this.recordEndTime(this.current);
      if (!this.answerTimes[this.current]?.startTime) {
        this.answerTimes[this.current] = {
          startTime: Date.now()
        };
      }
    },
    // 检查选项是否被选中
    isOptionSelected(question, option) {
      return question.selectedOption === option;
    },
    // 检查是否可以提交
    checkSubmitStatus() {
      this.canSubmit = this.questions.every(q => q.answered);
    },
    // 提交答案
    async handleSubmit() {
      if (!this.canSubmit) {
        uni.showToast({ title: '请完成所有题目后再提交', icon: 'none' });
        return;
      }

      try {
        const userInfo = uni.getStorageSync('userInfo');
        const answerDetails = this.questions.map((q, index) => {
          const answerTime = this.answerTimes[index] || {};
          return {
            questionId: q.id,
            userAnswer: q.selectedOption,
            startTimestamp: answerTime.startTime || Date.now(),
            endTimestamp: answerTime.endTime || Date.now()
          };
        });

        const res = await submitAnswers({
          uid: userInfo?.id || '',
          subjectId: this.subjectId,
          chapterId: this.chapterId,
          answerDetails
        });

        if (res.code === 200) {
          uni.showToast({ title: '提交成功', icon: 'success' });
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/question/result?result=' + encodeURIComponent(JSON.stringify(res.data))
            });
          }, 1500);
        } else {
          uni.showToast({ title: res.message || '提交失败', icon: 'none' });
        }
      } catch (err) {
        console.error('提交答案出错:', err);
        uni.showToast({ title: '提交失败', icon: 'none' });
      }
    },
    // 获取题目列表
    fetchQuestions() {
      if (!this.chapterId) {
        uni.showToast({ title: '章节ID缺失', icon: 'none' });
        return;
      }

      uni.request({
        url: `${getBaseUrl()}/question/getQuestionByChapterId/${this.chapterId}`,
        method: 'GET',
        success: (res) => {
          if (res.data.code === 200) {
            this.questions = res.data.data.map(question => ({
              ...question,
              answered: false,
              right: false,
              selectedOption: null
            }));
          } else {
            uni.showToast({ title: '获取题目失败', icon: 'none' });
          }
        },
        fail: () => {
          uni.showToast({ title: '请求失败', icon: 'none' });
        }
      });
    },
    // 记录题目结束时间
    recordEndTime(index) {
      const now = Date.now();
      if (!this.answerTimes[index]) {
        this.answerTimes[index] = {};
      }
      this.answerTimes[index].endTime = now;
    },
    // 记录题目开始时间
    recordStartTime(index) {
      const now = Date.now();
      if (!this.answerTimes[index]) {
        this.answerTimes[index] = {};
      }
      if (!this.answerTimes[index].startTime) {
        this.answerTimes[index].startTime = now;
      }
    }
  }
};
</script>

<style>
.question_card {
  background: white;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 110rpx;
  height: 60vh;
  box-shadow: 0 0 80rpx 8rpx #0000003d;
  display: flex;
  flex-wrap: wrap;
  padding: 30rpx;
  flex-direction: column;
  justify-content: space-between;
}

.question_card_submit {
  width: 40%;
  padding: 10rpx;
  margin: 0 auto;
}

.question_card_submit .submit_button {
  width: 100%;
  background: #5983ff;
  color: white;
  border-radius: 40rpx;
  font-size: 28rpx;
  padding: 10rpx 0;
}

.question_card_point {
  width: 70rpx;
  height: 70rpx;
  border: 2rpx solid #000000a6;
  color: #000000a6;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin: 20rpx;
}

.question_wrapper {
  background: linear-gradient(135deg, rgba(170, 207, 252, 1) 0%, rgba(187, 208, 251, 1) 50%, rgba(178, 236, 248, 1) 100%);
  min-height: 100vh;
}

.question_swiper {
  min-height: 100vh;
}

.question_content {
  padding: 30rpx;
  background: rgba(255, 255, 255, 0.8);
}

.question_item_name {
  font-size: 32rpx;
  color: #1d2342b0;
  letter-spacing: 1rpx;
  line-height: 50rpx;
}

.question_item_type {
  background: #5983ff;
  color: white;
  padding: 6rpx 16rpx;
  font-size: 24rpx;
  margin-right: 20rpx;
  border-radius: 10rpx;
}

.question_item_option {
  margin: 20rpx 0;
  font-size: 30rpx;
  padding: 20rpx;
  border-radius: 10rpx;
}

.question_item_option.selected {
  background: #f0f0f0;
}

.question_item_parse {
  margin-top: 30rpx;
  font-size: 28rpx;
  color: #000000ad;
}

.question_bar {
  position: fixed;
  left: 0;
  bottom: 0;
  right: 0;
  background: white;
  display: flex;
  align-items: center;
  padding: 20rpx 40rpx;
  z-index: 9999;
}

.question_bar_icon_wrapper {
  flex: 1;
}

.question_bar_icon {
  width: 36rpx;
  height: 36rpx;
}

.question_bar_info {
  color: #000000a3;
  font-size: 28rpx;
  text-align: center;
  flex: 3;
}

.current {
  background: #3493f9e6;
  color: white;
}

.right {
  background: #92df9a;
  color: white;
}

.error {
  background: #fba1a1;
  color: white;
}
</style>